package com.atguigu.yygh.hosp.controller.api;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.utils.HttpRequestHelper;
import com.atguigu.yygh.common.utils.MD5;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController("ApiHospitalController")
@RequestMapping("/api/hosp")
public class HospitalController {

    @Autowired
    private HospitalService hospitalService;

    @ApiOperation("获取医院信息")
    @PostMapping("/hospital/show")
    public Result<Hospital> showHospital(HttpServletRequest request){
//        获取参数信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = HttpRequestHelper.switchMap(parameterMap);
        String hoscode = (String) map.get("hoscode");

//        验证signKey
        String sign = (String) map.get("sign");
        String signKeyWithHosecode = hospitalService.getSignKeyWithHosecode(hoscode);
        String encrypt = MD5.encrypt(sign);
        if (StringUtils.isEmpty(sign) && StringUtils.isEmpty(encrypt) && !encrypt.equals(signKeyWithHosecode)){
            throw new YyghException(20001,"查询失败");
        }
//        通过医院编号获取医院信息
        Hospital hospital =  hospitalService.getHospitalByHoscode(hoscode);
        return Result.ok(hospital);
    }

    @ApiOperation("上传医院")
    @PostMapping("/saveHospital")
    public Result saveHospital(HttpServletRequest request){
//        获取所有的医院信息
        Map<String, Object> resultMap = HttpRequestHelper.switchMap(request.getParameterMap());
        String requestSignKey = (String) resultMap.get("sign");
        String requestHouseCode = (String) resultMap.get("hoscode");
        String platformSignKet = hospitalService.getSignKeyWithHosecode(requestHouseCode);
        String encrypt = MD5.encrypt(platformSignKet);

//        signKey 不能为空 并且必须相等 才能进行保存操作(验证目的:此信息是否真的经过授权)
        if(!StringUtils.isEmpty(requestSignKey) && !StringUtils.isEmpty(encrypt) && requestSignKey.equals(encrypt)){
//            读取图片信息(logodata)
            String logoData = (String) resultMap.get("logoData");
            String resultLogoData = logoData.replaceAll(" ", "+");
            resultMap.put("logoData",resultLogoData);

//        保存到Mongodb (保存的功能写到了ServerImpl层   )
            hospitalService.saveHospital(resultMap);
        }else{
            throw new YyghException(20001,"保存失败");
        }
        return Result.ok();
    }

}
